﻿using System;
using System.Collections.Generic;
using System.Reflection;
using MySql.Simple.Mapper.Readers;

namespace MySql.Simple.Mapper.Structures
{
    /// <summary>
    /// Represents a MySQL server instance
    /// </summary>
    public class Server
    {
        private readonly Connection connection;

        private IList<string> DatabaseNames
        {
            get
            {
                return StringReader.Read("SHOW DATABASES;", connection);   
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Server"/> class.
        /// </summary>
        /// <param name="connection">The connection.</param>
        public Server(Connection connection)
        {
            this.connection = connection;
        }

        public Database LoadDatabase(string databaseName, Assembly assembly)
        {
            if (Exists(databaseName))
            {
                return new Database(databaseName, assembly, connection);
            }
            else
            {
                throw new ApplicationException(string.Format("Database '{0}' does not exist on the server.", databaseName));
            }
        }

        /// <summary>
        /// Determines if a <see cref="Database"/> with the given name exists on the server.
        /// </summary>
        /// <param name="databaseName">Name of the database.</param>
        /// <returns></returns>
        public bool Exists(string databaseName)
        {
            var exists = false;

            foreach (var database in DatabaseNames)
            {
                if (string.Compare(database, databaseName, true) != 0) continue;

                exists = true;

                break;
            }

            return exists;
        }

        /// <summary>
        /// Drops the database with the specified name.
        /// </summary>
        /// <param name="databaseName">Name of the database.</param>
        public void Drop(string databaseName)
        {
            connection.ExecuteNonQuery(string.Format("DROP DATABASE `{0}`;", databaseName));            
        }

        /// <summary>
        /// Creates a database with the given name.
        /// </summary>
        public void Create(string databaseName)
        {
            connection.ExecuteNonQuery(string.Format("CREATE DATABASE `{0}`;", databaseName));
        }
    }
}
